import glob from 'glob'
import webpack from 'webpack'

import HtmlWebpackPlugin from 'html-webpack-plugin'
import ExtractTextPlugin from 'extract-text-webpack-plugin'
const webpackConfig = {
    entry: {
        common: './app/vendor/main.js'
    }, //已多次提及的唯一入口文件
    output: {
        path: __dirname + "/build",
        filename: "js/[name]-[hash].js"
    },
    devtool: 'none',
    devServer: {
        contentBase: "./app", //本地服务器所加载的页面所在的目录
        historyApiFallback: true, //不跳转
        inline: true,
        hot: true
    },
    module: {
        rules: [{
            test: /(\.jsx|\.js)$/,
            use: {
                loader: "babel-loader",
            },
            exclude: /node_modules/
        }, {
            test: /\.(scss|sass|css)$/,  // pack sass and css files
            loader: ExtractTextPlugin.extract({fallback: "style-loader", use: "css-loader!postcss-loader!sass-loader"})
        },{
            test: /\.(png|jpg)$/,
            loader: 'url-loader',
            options: {
                limit: '8196',
                name:'images/[name]-[hash].[ext]'
            }
        }, {
            test: /\.art$/,
            loader: "art-template-loader",
            options: {
                // art-template options (if necessary)
                // @see https://github.com/aui/art-template
            }
        }]
    },
    plugins: [
        new webpack.BannerPlugin('版权所有，翻版必究'),
        // new HtmlWebpackPlugin({
        //     template: __dirname + "/app/tmpl/index.tmpl.html" //new 一个这个插件的实例，并传入相关的参数
        // }),
        new webpack.optimize.OccurrenceOrderPlugin(),
        // new webpack.optimize.UglifyJsPlugin(),
        new ExtractTextPlugin('css/[name].css'),
        new webpack.ProvidePlugin({
            $: 'jquery',
            jQuery: 'jquery',
            'window.jQuery': 'jquery',
            'window.$': 'jquery',
        }),
        new webpack.optimize.CommonsChunkPlugin({
            name: "common",
            filename: "js/[name]-[hash].js"
        })
    ]
};

// 获取指定路径下的入口文件
function getEntries(globPath) {
    let files = glob.sync(globPath);
    let entries = {};

    files.forEach(function (filepath) {
        // 取倒数第二层(view下面的文件夹)做包名
        let split = filepath.split('/');
        let name = split[split.length - 2];

        entries[name] = './' + filepath;
    });

    return entries;
}

let entries = getEntries('app/pages/**/index.js');
Object.keys(entries).forEach(function (name) {
    // 每个页面生成一个entry，如果需要HotUpdate，在这里修改entry
    webpackConfig.entry[name] = entries[name];

    // 每个页面生成一个html
    let plugin = new HtmlWebpackPlugin({
        // 生成出来的html文件名
        filename: name + '.html',
        // 每个html的模版，这里多个页面使用同一个模版
        template: './app/index.html',
        // 自动将引用插入html
        inject: true,
        // 每个html引用的js模块，也可以在这里加上vendor等公用模块
        chunks: ['common', name]
    });
    webpackConfig.plugins.push(plugin);
});

export default webpackConfig;